package my.springboot3.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import my.springboot3.exception.errorException;
import my.springboot3.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


/**
 * 拦截器
 */
@Component
public class HeaderInterceptor implements HandlerInterceptor {

    // RedisService接口
    @Autowired
    private RedisService redisService;

    /**
     * 登录拦截器,在请求处理之前进行调用
     * @param request,请求
     * @param response,响应
     * @param handler,处理
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 1.验证请求头是否正确
            // 获取请求头中的特定字段
            String token = request.getHeader("Authorization");

            // 验证token完整性,验证失败则自动抛出异常
            Map<String, Object> map = JwtUtil.parseToken(token);

            // 获取redis键值id，取出token值做白名单验证
            // Integer id = (Integer) map.get("id");
            String id = map.get("id").toString();

            String checkToken = redisService.get(id);
            if(checkToken == null ||!token.equals(checkToken)){
                throw new errorException("token已过期,请重新登录");
            }

            // 2.对快过期的token进行续期
            if(redisService.getExpireTime(id) < 60 * 1000 * 10){
                // 续期
                redisService.set(id, token);
            }

            // 3.将当前用户信息id存储到ThreadLocal中
            ThreadLocalUtil.set(Integer.valueOf(id));
            // System.out.println("请求用户: "+ map.get("username").toString()
            //         +"\t线程: "+Thread.currentThread().getName()
            // +"\t"+ request.getRequestURL());
            // 4. 放行
            return true;
        } catch (Exception e) {

            // 验证失败,处理异常
            // 请求头不正确，设置响应状态码为401（未授权）,常量401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(e.getMessage());
            return false; // 请求头不正确，拒绝请求
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在请求处理完成后自动调用
        // 清除ThreadLocal中的存储
        ThreadLocalUtil.clear();
    }

}
